import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class ObjectMappingTool {

    /**
     * 将对象转换为JSON字符串
     * @param obj 要转换的对象
     * @return JSON格式的字符串
     */
    public static String objectToJson(Object obj) {
        if (obj == null) {
            return "{}";
        }

        Class<?> clazz = obj.getClass();
        StringBuilder json = new StringBuilder("{");
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue; // 跳过静态字段
            }

            field.setAccessible(true); // 确保可以访问私有字段
            try {
                String name = field.getName();
                Object value = field.get(obj);
                json.append("\"").append(name).append("\":");

                if (value == null) {
                    json.append("null,");
                } else if (value instanceof String) {
                    json.append("\"").append(value).append("\",");
                } else {
                    json.append(value).append(",");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (json.length() > 1) {
            json.setLength(json.length() - 1); // 去掉最后一个逗号
        }
        json.append("}");
        return json.toString();
    }

    /**
     * 将JSON字符串转换为对象
     * @param json JSON格式的字符串
     * @param clazz 目标类类型
     * @return 转换后的对象
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        if (json == null || json.isEmpty()) {
            return null;
        }

        Map<String, String> jsonMap = parseJson(json);
        T obj;
        try {
            obj = clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue; // 跳过静态字段
            }

            field.setAccessible(true); // 确保可以访问私有字段
            try {
                String name = field.getName();
                if (jsonMap.containsKey(name)) {
                    String value = jsonMap.get(name);
                    Object convertedValue = convertValue(value, field.getType());
                    field.set(obj, convertedValue);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 解析JSON字符串为键值对Map
     * @param json JSON格式的字符串
     * @return 包含键值对的Map
     * @throws IllegalArgumentException 如果JSON格式无效
     */
    private static Map<String, String> parseJson(String json) {
        Map<String, String> map = new HashMap<>();
        json = json.trim();
        if (!json.startsWith("{") || !json.endsWith("}")) {
            throw new IllegalArgumentException("Invalid JSON format");
        }

        json = json.substring(1, json.length() - 1).trim();
        String[] pairs = json.split(",");
        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            if (keyValue.length != 2) {
                throw new IllegalArgumentException("Invalid JSON format");
            }

            String key = keyValue[0].trim().replace("\"", "");
            String value = keyValue[1].trim();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 将字符串值转换为目标类型
     * @param value 字符串值
     * @param targetType 目标类型
     * @return 转换后的值
     * @throws IllegalArgumentException 如果类型不支持
     */
    private static Object convertValue(String value, Class<?> targetType) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        if (targetType == String.class) {
            return value.replace("\"", "");
        } else if (targetType == int.class || targetType == Integer.class) {
            return Integer.parseInt(value);
        } else if (targetType == double.class || targetType == Double.class) {
            return Double.parseDouble(value);
        } else if (targetType == boolean.class || targetType == Boolean.class) {
            return Boolean.parseBoolean(value);
        } else {
            throw new IllegalArgumentException("Unsupported type: " + targetType.getName());
        }
    }

    public static void main(String[] args) {
        // 测试对象转JSON
        Person person = new Person("Alice", 30);
        String json = objectToJson(person);
        System.out.println("Object to JSON: " + json);

        // 测试JSON转对象
        String jsonInput = "{\"name\":\"Bob\",\"age\":25}";
        Person personFromJson = jsonToObject(jsonInput, Person.class);
        if (personFromJson != null) {
            System.out.println("JSON to Object: " + personFromJson.getName() + ", " + personFromJson.getAge());
        }
    }
}

/**
 * 测试用的Person类
 */
class Person {
    private String name;
    private int age;

    public Person() {}

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}